#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QtCore/QDateTime>
#include <QtMqtt/QMqttClient>
#include <QtWidgets/QMessageBox>

using namespace Qt::StringLiterals;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    
    // 先创建MQTT客户端
    m_client = new QMqttClient(this);
    
    pageone=new Pageone(ui->widget_2);
    pageone->hide();
    page2=new pagetwo(ui->widget_2);
    page2->hide();
    page3=new pagethree(ui->widget_2);
    page3->hide();
    connect(pageone, &Pageone::temperatureChanged,
            page2, &pagetwo::onTemperatureReceived);
    connect(pageone, &Pageone::tempThresholdChanged,
            page2, &pagetwo::onTempThresholdReceived);
    connect(pageone, &Pageone::humidityChanged,
            page3, &pagethree::onHumidityReceived);
    
    // 将MQTT客户端传给pageone
    pageone->setMqttClient(m_client);
    
    connect(ui->action1,SIGNAL(triggered()),this,SLOT(connectPageone()));
    connect(ui->action2,SIGNAL(triggered()),this,SLOT(connectPagetwo()));
    connect(ui->action3,SIGNAL(triggered()),this,SLOT(connectPagethree()));
    m_client->setHostname(ui->lineEditHost_2->text());
    m_client->setPort(static_cast<quint16>(ui->spinBoxPort_2->value()));

    connect(m_client, &QMqttClient::stateChanged, this, &MainWindow::updateLogStateChange);
    connect(m_client, &QMqttClient::disconnected, this, &MainWindow::brokerDisconnected);
    
    // 连接主题输入框变化信号
    connect(ui->lineEditTopic_2, &QLineEdit::textChanged, this, &MainWindow::onTopicChanged);


    connect(m_client, &QMqttClient::messageReceived, this, [this](const QByteArray &message, const QMqttTopicName &topic) {
        const QString content = QDateTime::currentDateTime().toString()
        + " Received Topic: "_L1
            + topic.name()
            + " Message: "_L1
            + message
            + u'\n';
        //ui->editLog_2->insertPlainText(content);
    });

    connect(m_client, &QMqttClient::pingResponseReceived, this, [this]() {
        const QString content = QDateTime::currentDateTime().toString()
        + "PingResponse\n"_L1;
        //ui->editLog_2->insertPlainText(content);
    });

    connect(ui->lineEditHost_2, &QLineEdit::textChanged, m_client, &QMqttClient::setHostname);
    connect(ui->spinBoxPort_2, QOverload<int>::of(&QSpinBox::valueChanged), this, &MainWindow::setClientPort);
    updateLogStateChange();
    QFile file(":/qss/style.qss");
    if (file.open(QFile::ReadOnly | QFile::Text)) {
        QTextStream stream(&file);
        setStyleSheet(stream.readAll());
        file.close();
    }

}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::connectPageone()
{
    pageone->show();
    page2->hide();
    page3->hide();

}
void MainWindow::connectPagetwo()
{
    page2->show();
    pageone->hide();
    page3->hide();

}
void MainWindow::connectPagethree()
{
    page3->show();
    page2->hide();
    pageone->hide();

}

void MainWindow::on_buttonConnect_2_clicked()
{
    if (m_client->state() == QMqttClient::Disconnected) {
        ui->lineEditHost_2->setEnabled(false);
        ui->spinBoxPort_2->setEnabled(false);
        ui->buttonConnect_2->setText(tr("Disconnect"));
        m_client->connectToHost();
    } else {
        ui->lineEditHost_2->setEnabled(true);
        ui->spinBoxPort_2->setEnabled(true);
        ui->buttonConnect_2->setText(tr("Connect"));
        m_client->disconnectFromHost();
    }
}

void MainWindow::on_buttonQuit_2_clicked()
{
    QApplication::quit();
}

void MainWindow::updateLogStateChange()
{
    const QString content = QDateTime::currentDateTime().toString()
    + ": State Change"_L1
        + QString::number(m_client->state())
        + u'\n';
    //ui->editLog_2->insertPlainText(content);
    
    // 当MQTT连接成功时，触发pageone订阅主题
    if (m_client->state() == QMqttClient::Connected) {
        qDebug() << "MQTT连接成功，触发Pageone订阅主题";
        // 设置主题前缀为lineEditTopic_2的值
        pageone->setTopicPrefix(ui->lineEditTopic_2->text());
        pageone->subscribeTopics();
    }
}

void MainWindow::brokerDisconnected()
{
    ui->lineEditHost_2->setEnabled(true);
    ui->spinBoxPort_2->setEnabled(true);
    ui->buttonConnect_2->setText(tr("Connect"));
}

void MainWindow::onTopicChanged()
{
    // 当主题输入框内容变化时，更新pageone的主题前缀
    if (pageone) {
        pageone->setTopicPrefix(ui->lineEditTopic_2->text());
        qDebug() << "主题已更新为:" << ui->lineEditTopic_2->text();
    }
}

void MainWindow::setClientPort(int p)
{
    m_client->setPort(static_cast<quint16>(p));
}

void MainWindow::on_buttonSubscribe_2_clicked()
{
    QString topic = ui->lineEditTopic_2->text();
    auto subscription = m_client->subscribe(topic);
    if (!subscription) {
        QMessageBox::critical(this, u"Error"_s,
                              u"Could not subscribe. Is there a valid connection?"_s);
        return;
    }
}


